package backend_store

import (
	"context"
	"xialou_platform/app/respx"
	"xialou_platform/app/tools"
	"xialou_platform/services/agent/rpc/agentClient"

	"xialou_platform/services/agent/api/internal/svc"
	"xialou_platform/services/agent/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type StoreReviewListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewStoreReviewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) StoreReviewListLogic {
	return StoreReviewListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *StoreReviewListLogic) StoreReviewList(req *types.StoreReviewListReq) (resp *respx.PageResp, err error) {

	list, err := l.svcCtx.AgentRpc.StoreList(l.ctx, &agentClient.StoreListReq{
		Page:     req.Page,
		PageSize: req.PageSize,
		Keyword:  req.Keyword,
		Status:   req.Status,
		Platform: req.Platform,
	})
	if err != nil {
		return nil, err
	}
	res := make([]*types.StoreReviewListResp, 0)
	for _, store := range list.List {
		agentParam, err := l.svcCtx.AgentRpc.AgentById(l.ctx, &agentClient.IdBody{Id: store.AgentId})
		if err != nil {
			return nil, err
		}

		storeLog, err := l.svcCtx.AgentRpc.StoreLogLatestByStoreId(l.ctx, &agentClient.IdBody{
			Id: store.StoreId,
		})
		if err != nil {
			return nil, err
		}

		storeCount, err := l.svcCtx.AgentRpc.StoreCount(l.ctx, &agentClient.StoreCountReq{
			AgentId:  store.AgentId,
			Platform: store.Platform,
			StoreId:  store.StoreId,
			Status:   -1,
		})
		if err != nil {
			return nil, err
		}

		temp := &types.StoreReviewListResp{
			Id:              respx.IDFrom(store.Id).ToString(),
			Name:            store.Name,
			BusinessLicense: store.BusinessLicense,
			IndustryLicense: store.IndustryLicense,
			AgentName:       agentParam.RealName,
			EquityPrice:     store.EquityPrice,
			AgentPhone:      agentParam.Phone,
			StorePhone:      store.StorePhone,
			SupportTakeaway: store.SupportTakeaway,
			PackingFee:      store.PackingFee,
			CreateTime:      tools.TimeUnixShowLayoutString(store.CreateTime),
			Version:         storeCount.Count,
			Status:          storeLog.Status,
			Reviewer:        storeLog.Remark,
		}

		res = append(res, temp)
	}

	return respx.NewPageResp(req.Page, req.PageSize, list.Total, res), nil
}
